package com.amap.map.location;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.map.R;
import com.amap.map.offlinemap.OfflineMapActivity;
import com.amap.map.route.RouteActivity;
import com.amap.map.util.OffLineMapUtils;
import com.amap.map.util.dialog.DialogUtil;
import com.amap.map.util.locationSource.LocationSourceProxy;
import com.amap.map.util.version.VersionUtils;

/**
 * AMapV2地图中介绍定位三种模式的使用，包括定位，追随，旋转
 * 
 * liuxing
 */
public class LocationModeSourceActivity extends Activity implements OnCheckedChangeListener{
	private AMap aMap;
	private MapView mapView;
    
	private Activity activy ;
    /** 菜单图片 **/
   	int[] menu_image_array = { R.drawable.menu_downmanager,
								R.drawable.menu_routesearch,
   								R.drawable.menu_checkupdate, 
   								R.drawable.menu_about,
   								R.drawable.menu_quit };
    String[] menu_name_array = {  "离线地图", "路线规划","检查更新", "关于", "退出" };
    View menuView;
    AlertDialog menuDialog;// menu菜单Dialog
    GridView menuGrid;  //http://www.cnblogs.com/over140/archive/2010/10/19/1855366.html
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.locationmodesource_activity);
        /*
         * 设置离线地图存储目录，在下载离线地图或初始化地图设置;
         * 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
         * 则需要在离线地图下载和使用地图页面都进行路径设置
         * */
		MapsInitializer.sdcardDir = OffLineMapUtils.getSdCacheDir(this) ;
		try {
			MapsInitializer.initialize(getBaseContext());		//没有网络的情况会自动加载本地的地图服务
		} catch (RemoteException e) {}
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		activy = this ;
		loadPhoneStatus() ;
		init();
		initMenu() ;
	}

	/**
	 * 初始化
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			aMap.setLocationSource( new LocationSourceProxy(aMap, getBaseContext()) );			// 设置定位数据来源
		}
	}
	
	/****
	 * 初始化菜单管理项
	 */
	private void initMenu(){
		menuView = View.inflate(this, R.layout.gridview_menu, null);
		menuDialog = new AlertDialog.Builder(this).create();
		menuDialog.setView(menuView);
		//设置dialog弹出的位置  http://blog.csdn.net/csh159/article/details/8127362
		Window window = menuDialog.getWindow();        
		window.setGravity( Gravity.BOTTOM );
		menuDialog.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU)// 监听按键
					dialog.dismiss();
				return false;
			}
		});
		menuGrid = (GridView) menuView.findViewById(R.id.gridview);
		menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));
		/** 监听menu选项 **/
		menuGrid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:	//下载管理
					//ToastUtil.show( getApplicationContext() , "您点击了下载管理menu" );
					startActivity( new Intent( getApplicationContext(), OfflineMapActivity.class ) );
					break;
				case 1://路线规划
					startActivity( new Intent( getApplicationContext(), RouteActivity.class ) );
					break;
				case 2:// 检查更新
					//ToastUtil.show( getApplicationContext() , "您点击了检查更新menu" );
					new VersionUtils( activy ) ;
					break;
				case 3:// 关于
					showDialog( DialogUtil.ABOUT_DIALOG_ID ) ;
					break;
				case 4://退出
					//ToastUtil.show( getApplicationContext() , "您点击了退出menu" );
					android.os.Process.killProcess(android.os.Process.myPid()) ;   //获取PID 
					System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
					break;
				}
				
				
			}
		});
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {		
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		//deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	/****
	 * 加载手机相应的信息
	 */
	private void loadPhoneStatus(){ 
		if( com.amap.map.util.Configuration.IEMI_NAME == null ){
			TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); 
			try {
				com.amap.map.util.Configuration.IEMI_NAME = Long.parseLong( phoneMgr.getDeviceId() ); 	//国际通用标识 
				com.amap.map.util.Configuration.MOBILE_NAME = Long.parseLong( phoneMgr.getLine1Number() );	//本机电话号码 
			} catch (NumberFormatException e) {}
		}
	}
	
	/***
	 * menu菜单的处理
	 * @param menuNameArray
	 * @param imageResourceArray
	 * @return
	 */
	private SimpleAdapter getMenuAdapter(String[] menuNameArray,
			int[] imageResourceArray) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < menuNameArray.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemImage", imageResourceArray[i]);
			map.put("itemText", menuNameArray[i]);
			data.add(map);
		}
		SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
				R.layout.item_menu, new String[] { "itemImage", "itemText" },
				new int[] { R.id.item_image, R.id.item_text });
		return simperAdapter;
	}
	
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (menuDialog == null) {
			menuDialog = new AlertDialog.Builder(this).setView(menuView).show();
		} else {
			menuDialog.show();
		}
		return false;// 返回为true 则显示系统menu
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");// 必须创建一项
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch(id)
		{
		case DialogUtil.ABOUT_DIALOG_ID :
		{
			return new AlertDialog.Builder( LocationModeSourceActivity.this )
            .setIcon(R.drawable.about_dialog_icon)
            .setTitle(R.string.about_title_name)
            .setMessage(R.string.about_content)
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                }
            }).create();
		}
		default:
			break;
		}
		
		return null;
	}

}
